# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - 认证视图
视图层，用户认证相关的路由处理
支持登录、登出、学员注册、教练注册等功能
"""

import os
from flask import Blueprint, render_template, request, redirect, url_for, flash, current_app
from flask_login import login_user, logout_user, login_required, current_user
from werkzeug.utils import secure_filename
from app.forms.auth_forms import LoginForm, StudentRegistrationForm, CoachRegistrationForm, PasswordChangeForm
from app.models.user import User
from app.models.campus import Campus
from app.models.account import UserAccount
from app import db
from datetime import datetime

# 创建认证蓝图
auth_bp = Blueprint('auth', __name__)


@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    """
    用户登录页面和处理

    GET: 显示登录表单
    POST: 处理登录请求
    """
    # 如果用户已登录，重定向到仪表板
    if current_user.is_authenticated:
        return redirect(url_for('dashboard.index'))

    form = LoginForm()

    if request.method == 'POST':
        if form.validate_on_submit():
            user = form.get_user()
            if user:

                # 登录用户
                login_user(user, remember=form.remember_me.data)

                flash(f'欢迎回来，{user.real_name}！', 'success')

                # 重定向到下一页或仪表板
                next_page = request.args.get('next')
                if next_page:
                    return redirect(next_page)
                return redirect(url_for('dashboard.index'))
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(error, 'error')

    return render_template('auth/login.html', form=form)


@auth_bp.route('/student/register', methods=['GET', 'POST'])
def student_register():
    """
    学员注册页面和处理

    GET: 显示学员注册表单
    POST: 处理学员注册请求
    """
    # 如果用户已登录，重定向到仪表板
    if current_user.is_authenticated:
        return redirect(url_for('dashboard.index'))

    form = StudentRegistrationForm()

    if request.method == 'POST':
        if form.validate_on_submit():
            try:
                # 创建新学员用户
                user = User(
                    username=form.username.data,
                    real_name=form.real_name.data,
                    phone=form.phone.data,
                    email=form.email.data if form.email.data else None,
                    gender=form.gender.data if form.gender.data else None,
                    age=form.age.data if form.age.data else None,
                    campus_id=form.campus_id.data,
                    role='student',
                    status='active'
                )
                user.set_password(form.password.data)

                db.session.add(user)
                db.session.flush()  # 获取用户ID

                # 创建用户账户
                account = UserAccount(
                    user_id=user.id,
                    balance=0.00
                )
                db.session.add(account)

                db.session.commit()

                flash('注册成功！请使用用户名和密码登录。', 'success')
                return redirect(url_for('auth.login'))

            except Exception as e:
                db.session.rollback()
                flash('注册失败，请稍后重试。', 'error')
                current_app.logger.error(f'Student registration error: {str(e)}')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(error, 'error')

    return render_template('auth/student_register.html', form=form)


@auth_bp.route('/coach/register', methods=['GET', 'POST'])
def coach_register():
    """
    教练注册页面和处理

    GET: 显示教练注册表单
    POST: 处理教练注册请求
    """
    # 如果用户已登录，重定向到仪表板
    if current_user.is_authenticated:
        return redirect(url_for('dashboard.index'))

    form = CoachRegistrationForm()

    if request.method == 'POST':
        if form.validate_on_submit():
            try:
                # 处理照片上传
                photo_url = None
                if form.photo.data:
                    photo_file = form.photo.data
                    if photo_file.filename != '':
                        # 确保上传目录存在
                        upload_dir = os.path.join(current_app.root_path, 'static', 'uploads', 'coaches')
                        os.makedirs(upload_dir, exist_ok=True)

                        # 生成安全的文件名
                        filename = secure_filename(photo_file.filename)
                        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
                        filename = f"{timestamp}_{filename}"

                        # 保存文件
                        photo_path = os.path.join(upload_dir, filename)
                        photo_file.save(photo_path)
                        photo_url = f"/static/uploads/coaches/{filename}"

                # 根据教练级别设置费率
                coach_rates = {
                    'junior': 80.00,
                    'middle': 150.00,
                    'senior': 200.00
                }

                # 创建新教练用户
                user = User(
                    username=form.username.data,
                    real_name=form.real_name.data,
                    phone=form.phone.data,
                    email=form.email.data if form.email.data else None,
                    gender=form.gender.data if form.gender.data else None,
                    age=form.age.data if form.age.data else None,
                    campus_id=form.campus_id.data,
                    role='coach',
                    status='pending',  # 教练需要审核
                    coach_level=form.coach_level.data,
                    hourly_rate=coach_rates[form.coach_level.data],
                    bio=form.bio.data,
                    experience=form.experience.data,
                    photo_url=photo_url
                )
                user.set_password(form.password.data)

                db.session.add(user)
                db.session.commit()

                flash('申请已提交！请等待校区管理员审核，审核通过后即可登录使用。', 'success')
                return redirect(url_for('auth.login'))

            except Exception as e:
                db.session.rollback()
                flash('申请提交失败，请稍后重试。', 'error')
                current_app.logger.error(f'Coach registration error: {str(e)}')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(error, 'error')

    return render_template('auth/coach_register.html', form=form)


@auth_bp.route('/logout')
@login_required
def logout():
    """
    用户登出处理
    """
    user_name = current_user.real_name
    logout_user()
    flash(f'再见，{user_name}！您已安全退出。', 'info')
    return redirect(url_for('auth.login'))


@auth_bp.route('/register')
def register():
    """
    注册选择页面

    用户可以选择注册为学员或教练
    """
    # 如果用户已登录，重定向到仪表板
    if current_user.is_authenticated:
        return redirect(url_for('dashboard.index'))

    # 获取所有活跃校区
    campuses = Campus.query.filter_by(status='active').all()

    return render_template('auth/register.html', campuses=campuses)
